package iblink.junit;

import iblink.adapter.IBClient;
import iblink.adapter.IBClientFactory;

import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;

public class TestConnection extends Assert {

	@Test
	public void ConnectToIBWithOneClient() {
		ConnectToIBWithNClients(1);
		assertTrue(true);
	}

	@Test
	public void ConnectToIBWith8Clients() {
		ConnectToIBWithNClients(8);
		assertTrue(true);
	}

	public void ConnectToIBWithNClients(int numClients) {

		IBClientFactory clientFactory = TestHelper.getIBClientFactory();

		List<IBClient> clients = new ArrayList<IBClient>();

		for (int i = 0; i < numClients; i++) {
			IBClient client = clientFactory.createIBClient();
			clients.add(client);
			client.connect();
		}

		for (int i = 0; i < numClients; i++) {
			clients.get(i).disconnect();
		}
	}

	// TODO: investigate why this fails only after running the other test
	// classes
	@Test
	public void connectAndDisconnectManyTimesWithManyClients() {

		int numClients = 8;

		IBClientFactory clientFactory = TestHelper.getIBClientFactory();

		List<IBClient> clients = new ArrayList<IBClient>();

		for (int i = 0; i < numClients; i++) {
			IBClient client = clientFactory.createIBClient();
			clients.add(client);
		}

		for (int i = 0; i < 10; i++) {
			IBClient c = clients.get((int) Math.floor(Math.random()
					* numClients));
			if (c.isConnected()) {
				c.disconnect();
			} else {
				c.connect();
			}
		}

		for (int i = 0; i < numClients; i++) {
			if (clients.get(i).isConnected()) {
				clients.get(i).disconnect();
			}
		}
		assertTrue(true);

	}

}
